package com.zzyk.main.configuration.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.zzyk.main.configuration.jwt.JwtDefaultSubjectFactory;
import com.zzyk.main.configuration.shiro.filter.GenericFilter;
import com.zzyk.main.configuration.shiro.filter.JwFilter;
import com.zzyk.main.configuration.shiro.filter.LogoutFilter;
import com.zzyk.main.configuration.shiro.realm.JwtRealm;
import com.zzyk.main.configuration.shiro.realm.UserRealm;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.mgt.*;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.crazycake.shiro.RedisCacheManager;
import org.crazycake.shiro.RedisManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * Shiro权限管理配置类
 */
@Configuration
@Log4j2
public class ShiroConfig {
    @Value("${spring.redis.host}")
    private String redisHost;
    @Value("${spring.redis.port}")
    private int redisPort;
    @Value("${spring.redis.password}")
    private String redisPassword;

    /**
     * 登录页面的URL
     */
    @Value("${shiro.url.login}")
    private String loginUrl;
    /**
     * 主页URL 认证成功会跳到这里
     */
    @Value("${shiro.url.index}")
    private String indexUrl;

    /**
     * 认证失败的URL 我这里其实还是跳到了登录页面
     */
    @Value("${shiro.url.unauthorized}")
    private String unauthorizedUrl;

    /**
     * shiro-thymeleaf标签
     *
     * @return
     */
    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect() {
        return new ShiroDialect();
    }

    /*
     * a. 告诉shiro不要使用默认的DefaultSubject创建对象，因为不能创建Session
     * */
    @Bean
    public SubjectFactory subjectFactory() {
        return new JwtDefaultSubjectFactory();
    }

    /**
     * JwtRealm 配置，需实现 Realm 接口
     */
    @Bean
    JwtRealm jwtRealm() {
        JwtRealm jwtRealm = new JwtRealm();
        return jwtRealm;
    }

    /**
     * ShiroRealm 配置，需实现 Realm 接口
     */
    @Bean
    UserRealm userRealm() {
        UserRealm userRealm = new UserRealm();
        return userRealm;
    }


    /**
     * 配置shiro redisManager
     * 使用的是shiro-redis开源插件
     */
    public RedisManager redisManager() {
        log.debug("RedisHost[{}]", redisHost);
        log.debug("RedisPord[{}]", redisPort);
        RedisManager redisManager = new RedisManager();
        redisManager.setHost(redisHost);
        redisManager.setPort(redisPort);
        redisManager.setTimeout(30000);//连接redis超时
        if (!StringUtils.isEmpty(redisPassword)) {
            redisManager.setPassword(redisPassword);
        }
        return redisManager;
    }

    @Bean(name = "securityManager")
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 2.Realm
//        List<Realm> realms = new ArrayList<Realm>(16);
//        realms.add(jwtRealm());
//        realms.add(userRealm());
//        securityManager.setRealms(realms);
        securityManager.setRealm(jwtRealm());
        // 3.关闭shiro自带的session
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        subjectDAO.setSessionStorageEvaluator(sessionStorageEvaluator());
        securityManager.setSubjectDAO(subjectDAO);
        securityManager.setSubjectFactory(subjectFactory());
        securityManager.setCacheManager(cacheManager());
        return securityManager;
    }

    /**
     * 禁用session, 不保存用户登录状态。保证每次请求都重新认证
     */
    @Bean
    protected SessionStorageEvaluator sessionStorageEvaluator() {
        DefaultSessionStorageEvaluator sessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        sessionStorageEvaluator.setSessionStorageEnabled(false);
        return sessionStorageEvaluator;
    }

    @Bean(name = "shiroFilter")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager) {
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);
        // 设置登录界面URL
        factoryBean.setLoginUrl(loginUrl);
        // 设置未经认证页面的URL
        factoryBean.setUnauthorizedUrl(unauthorizedUrl);
        // 设置登录成功后跳转的URL
        factoryBean.setSuccessUrl(indexUrl);

        HashMap<String, Filter> filter = new HashMap<>();
        filter.put("jwt", new JwFilter());
        filter.put("authc", new GenericFilter());
        filter.put("logout", new LogoutFilter());
        factoryBean.setFilters(filter);
        // 需要认证的加到authc里面
        // 不需要认证的加到anon里面
        LinkedHashMap<String, String> filterChain = new LinkedHashMap<>();
        filterChain.put("/", "anon");
        filterChain.put("/ws/**", "anon");
        filterChain.put("/test/**", "anon");
        filterChain.put("/sys/**", "anon");
        filterChain.put("/api/**", "anon");
        filterChain.put("/message/**", "anon");
        filterChain.put("/**/verificationDeviceByNumber2", "anon");
        filterChain.put("/**/verificationDeviceByNumber", "anon");
        filterChain.put("/**/verificationDeviceByClientID", "anon");
        filterChain.put("/**/uniqueCollectionEquipment", "anon");
        filterChain.put("/**/saveCollectionEquipment", "anon");
        filterChain.put("/**/exportProductionDetails", "anon");
        filterChain.put("/**/getInfoListExcel", "anon");
        filterChain.put("/**/uniqueName", "anon");
        filterChain.put("/sys/logout", "logout");
        filterChain.put("/**/customize/**", "anon");
        filterChain.put("/**/layuiadmin/**", "anon");
        filterChain.put("/**/plugins/**", "anon");
        filterChain.put("/**/**.html", "anon");
        filterChain.put("/**/forgetPassword.html", "anon");
        filterChain.put("/**/regist.html", "anon");
        filterChain.put("/**/favicon.ico", "anon");
        filterChain.put("/**", "jwt");
        factoryBean.setFilterChainDefinitionMap(filterChain);
        return factoryBean;
    }

    /**
     * 配置 ModularRealmAuthenticator
     */
    @Bean
    public ModularRealmAuthenticator authenticator() {
        ModularRealmAuthenticator authenticator = new MultiRealmAuthenticator();
        // 设置多 Realm的认证策略，默认 AtLeastOneSuccessfulStrategy
        AuthenticationStrategy strategy = new FirstSuccessfulStrategy();
        authenticator.setAuthenticationStrategy(strategy);
        return authenticator;
    }

    /**
     * cacheManager 缓存 redis实现
     * 使用的是shiro-redis开源插件
     */
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager();
        redisCacheManager.setRedisManager(redisManager());
        //缓存过期时间：秒
        redisCacheManager.setExpire(1800);
        return redisCacheManager;
    }

    /**
     * 开启Shiro的注解(如@RequiresRoles,@RequiresPermissions),需借助SpringAOP扫描使用Shiro注解的类,并在必要时进行安全逻辑验证
     * <p>
     * 配置以下两个bean(DefaultAdvisorAutoProxyCreator和AuthorizationAttributeSourceAdvisor)即可实现此功能
     *
     * @return
     */

    @Bean

    public DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator() {

        DefaultAdvisorAutoProxyCreator advisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();

        advisorAutoProxyCreator.setProxyTargetClass(true);

        return advisorAutoProxyCreator;

    }

    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
}
